var p []int

func minMalwareSpread(graph [][]int, initial []int) int {
	n := len(graph)
	p = make([]int, n)
	size := make([]int, n)
	clean := make([]bool, n)
	for i := 0; i < n; i++ {
		p[i] = i
		size[i] = 1
		clean[i] = true
	}
	for _, i := range initial {
		clean[i] = false
	}
	for i := 0; i < n; i++ {
		if !clean[i] {
			continue
		}
		for j := i + 1; j < n; j++ {
			if !clean[j] {
				continue
			}
			if graph[i][j] == 1 {
				pa, pb := find(i), find(j)
				if pa == pb {
					continue
				}
				p[pa] = pb
				size[pb] += size[pa]
			}
		}
	}
	cnt := make([]int, n)
	mp := make(map[int]map[int]bool)
	for _, i := range initial {
		s := make(map[int]bool)
		for j := 0; j < n; j++ {
			if !clean[j] {
				continue
			}
			if graph[i][j] == 1 {
				s[find(j)] = true
			}
		}
		for e, _ := range s {
			cnt[e]++
		}
		mp[i] = s
	}
	mx, res := -1, 0
	for i, s := range mp {
		t := 0
		for e, _ := range s {
			if cnt[e] == 1 {
				t += size[e]
			}
		}
		if mx < t || (mx == t && i < res) {
			mx, res = t, i
		}
	}
	return res
}

func find(x int) int {
	if p[x] != x {
		p[x] = find(p[x])
	}
	return p[x]
}